package com.czl.module_work.adapter


import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseDataBindingHolder
import com.czl.base.data.bean.MembersBean
import com.czl.module_work.R
import com.czl.module_work.databinding.WorkFragmentMembersSelectBinding
import com.czl.module_work.databinding.WorkItemMembersSelectBinding
import com.czl.module_work.databinding.WorkItemTakeCareOrderBinding

class MembersSelectAdapter :
    BaseQuickAdapter<MembersBean, BaseDataBindingHolder<WorkItemMembersSelectBinding>>(R.layout.work_item_members_select) {
    private val maxSelectCount  = 5

    private var selectPos = -1

    private var selectPosArray = arrayListOf<String>()

    private var isSelectMode = true

    private var isSingle = true
    fun setSelectMode(isSelectMode: Boolean) {
        this.isSelectMode = isSelectMode
    }

    fun setIsSingle(isSingle: Boolean) {
        this.isSingle = isSingle
    }

    override fun convert(
        holder: BaseDataBindingHolder<WorkItemMembersSelectBinding>,
        roomItem: MembersBean
    ) {
        holder.dataBinding?.apply {
            item = roomItem.nickName
            if (!isSingle) {
                isSelected = selectPosArray.contains(holder.adapterPosition.toString())
            } else {
                isSelected = selectPos == holder.adapterPosition
            }
            executePendingBindings()
        }
        if (isSelectMode) {
            holder.itemView.setOnClickListener {
                if (isSingle) {
                    selectPos = holder.absoluteAdapterPosition
                } else {
                    if (selectPosArray.contains(holder.absoluteAdapterPosition.toString())) {
                        selectPosArray.remove(holder.absoluteAdapterPosition.toString())
                    } else {
                        if(selectPosArray.size >= maxSelectCount){
                            return@setOnClickListener
                        }
                        selectPosArray.add(holder.absoluteAdapterPosition.toString())
                    }
                }
                notifyDataSetChanged()
            }
        }
    }

    fun getSelectMembers(): List<MembersBean> {
        val result = arrayListOf<MembersBean>()
        if (isSingle) {
            if (selectPos == -1) return listOf()
            result.add(data.get(selectPos))
        } else {
            selectPosArray.forEach {
                result.add(data.get(it.toInt()))
            }
        }
        return result
    }
}